package com.dst.smart.json;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import android.text.TextUtils;

import com.dst.smart.app.MyApplication;
import com.dst.smart.model.AnHong;

public class AnHongUitils {
	public static List<AnHong> list = new ArrayList<AnHong>();
	private static File jsonFile = new File(MyApplication.getInstance()
			.getRootPath() + File.separator + "a_json");
	static {
		if (list.size() == 0) {
			String json = JSONFileUtils.getJsonStringFromFile(jsonFile)
					.replace("\r\n", "");
			if (TextUtils.isEmpty(json)) {
				initAnHong();
				save();
			} else {
				try {
					JSONArray jsonArray = new JSONArray(json);

					for (int i = 0; i < jsonArray.length(); i++) {
						JSONObject object = jsonArray.getJSONObject(i);
						AnHong anHong = new AnHong();
						anHong.setId(object.getInt("Id"));
						anHong.setMsgName(object.getString("MsgName"));
						anHong.setMsgInfo(object.getString("MsgInfo"));

						list.add(anHong);
					}
				} catch (Exception e) {
					// TODO: handle exceptionus
					initAnHong();
					save();
				}
			}
		}
	}

	public static String getString() {
		return JSONFileUtils.getJsonStringFromFile(jsonFile)
				.replace("\r\n", "");
	}

	public static void save() {
		try {

			JSONArray array = new JSONArray();
			for (AnHong anHong : list) {
				JSONObject bject = new JSONObject();
				bject.put("Id", anHong.getId());
				bject.put("MsgName", anHong.getMsgName());
				bject.put("MsgInfo", anHong.getMsgInfo());
				array.put(bject);
			}
			JSONFileUtils.saveJSONToFile(jsonFile, array.toString());
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

	public static void initAnHong() {
		for (int i = 0; i < 32; i++) {
			AnHong anHong = new AnHong();
			anHong.setId(i);
			if (i == 0) {
				anHong.setMsgName("煤气");
				anHong.setMsgInfo("煤气");

			} else if (i > 0 && i < 4) {
				anHong.setMsgName("火警" + i);
				anHong.setMsgInfo("火警" + i);
			} else if (i > 3 && i < 8) {
				anHong.setMsgName("求救" + (i - 3));
				anHong.setMsgInfo("求救" + (i - 3));
			} else {
				anHong.setMsgName("未定义" + (i - 8));
				anHong.setMsgInfo("未定义" + (i - 8));
			}
			list.add(anHong);
		}
	}

	public static String getAnHong(int Id) {
		String anHong = "安防报警";
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getId() == Id) {
				anHong = list.get(i).getMsgInfo();
				break;
			}
		}
		return anHong;
	}

	public static int setAnHong(AnHong anHong) {
		int result = 0;
		for (AnHong _AnHong : list) {
			if (_AnHong.getId() == anHong.getId()) {
				_AnHong.setMsgName(anHong.getMsgName());
				_AnHong.setMsgInfo(anHong.getMsgInfo());
				result = 1;
				break;
			}
		}
		save();
		return result;
	}

}
